#include "StdAfx.h"
#include "sqlsafe.h"


SafeSQL::SafeSQL() :m_pSQL(NULL), m_pSQLSafe(NULL)
{
}

SafeSQL::SafeSQL(char* pSQL) : m_pSQLSafe(NULL)
{
	int len = strlen(pSQL);
	char* pNatSQL = new char[len + 1];
	pNatSQL[len] = '\0';
	memcpy(pNatSQL, pSQL, len);
	m_pSQL = pNatSQL;
}

SafeSQL::~SafeSQL()
{
	if (m_pSQL)
		delete m_pSQL;
	if (m_pSQLSafe)
		delete m_pSQLSafe;
}

int SafeSQL::GetSafeSQL()
{
	int safelen = GetSafeSQLLength();
	int i = 0;
	char* pSafeSQL = new char[safelen+1];
	pSafeSQL[safelen] = '\0';
	int len = strlen(m_pSQL);
	int offset = 0;
	for (; i < len; i++)
	{
		if (m_pSQL[i] == '\'')
		{
			if (i != 0)
			{
				if (m_pSQL[i - 1] == '\\')
				{
					continue;
				}
			}
			pSafeSQL[i + offset] = '\\';
			offset++;
		}
		pSafeSQL[i + offset] = *(m_pSQL+i);
	}
	m_pSQLSafe = pSafeSQL;
	return TRUE;
}
char* SafeSQL::GetSafePtr()
{
	return m_pSQLSafe;
}
int SafeSQL::GetSafeSQLLength()
{
	char* pSQL = m_pSQL;
	int i = 0;
	int len = strlen(pSQL);
	int safe_len = 0;
	for (; i < len; i++)
	{
		safe_len++;
		if (*(pSQL + i) == '\'')
		{
			safe_len++;
		}
	}
	return safe_len;
}
